<?php

/**
 * Role class
 */
class Role extends SM_ADMIN_Controller
{

    //assign $var to this field
    private $_data;

    /**
     * Initialization
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->model('role_model');
    }

    /**
     * show role listing
     */
    public function index()
    {
        $breadcrumb = array(
            array('link' => admin_url('index'), 'name' => $this->lang->line('Home')),
            array('link' => admin_url('role/index'), 'name' => 'View role', 'class' => 'active')
        );
        $this->_data['breadcrumb'] = $breadcrumb;
        $this->_data['roles'] = $this->role_model->getAll();
        $this->load->view('layout/main', array('content' => 'role/index', 'data' => $this->_data));
    }

    /**
     * Edit role by id
     * @param int $role_id
     */
    public function form($role_id = '')
    {
        $breadcrumb = array(
            array('link' => admin_url('index'), 'name' => $this->lang->line('Home')),
            array('link' => admin_url('role/index'), 'name' => 'Role'),
            array('link' => admin_url('role/form'), 'name' => 'Add role', 'class' => 'active')
        );
        $this->_data['breadcrumb'] = $breadcrumb;
        $info = '';
        if (!empty($role_id)) {
            $info = $this->role_model->getRole($role_id);
            $this->_data['info'] = $info;
        }
        $this->load->helper('role');
        $this->load->library('form_validation');
        $this->form_validation->set_rules(form_role_field_validate());
        if ($this->form_validation->run()) {
            $form = $this->input->post();
            if (isset($form['submit'])) {

                $data = array(
                    'role_name' => $form['role_name'],
                    'role_title' => $form['role_title'],
                    'role_rule' => json_encode($form['role_rule'])
                );
                if (!empty($role_id)) {
                    $this->role_model->updateRole($role_id, $data);
                } else {
                    $this->role_model->addRole($data);
                }
                redirect_admin('role/index');
            }
        }
        $this->load->model('module_model');
        $module = $this->module_model->getList();
        $this->_data['module'] = $module;
        $this->_data['form'] = form_role_field($info);
        $this->load->view('layout/main', array('content' => 'role/form', 'data' => $this->_data));
    }

}
